package com.example.win.android_banduyujia.login.view;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ViewFlipper;

import com.example.win.android_banduyujia.R;
import com.example.win.android_banduyujia.http.UrlContext;
import com.example.win.android_banduyujia.http.request.RegisterRequest;
import com.example.win.android_banduyujia.http.request.VerifyCodeRequest;
import com.example.win.android_banduyujia.http.response.BaseHttpResponse;
import com.example.win.android_banduyujia.entity.Constants;
import com.example.win.android_banduyujia.lib.util.StrUtils;
import com.example.win.android_banduyujia.peopleactivity.activity.activity.PhotoMyActivity;
import com.example.win.android_banduyujia.peopleactivity.activity.activity.WelcomeActivity;
import com.example.win.android_banduyujia.peopleactivity.ui.activity.BaseTitleBarActivity;
import com.umeng.analytics.MobclickAgent;

/**
 * Created by Win on 2015/8/6.
 */
public class RegisteredActivity extends BaseTitleBarActivity implements View.OnClickListener {

    private final static int REGISTER_PAGE_1 = 0;
    private final static int REGISTER_PAGE_2 = 1;
    private final static int REGISTER_PAGE_3 = 2;

    private ViewFlipper  mFlipper;

    private EditText  mEditPhone;
    private Button    mBtnNextStep1;

    private EditText  mEditCode;
    private Button    mBtnCode;
    private Button    mBtnNextStep2;

    private EditText  mEditPassword;
    private Button    mButtonRegister;

    private String    mUserName;
    private String    mValidCode;
    private String    mPassword;
    private String    mDevices;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_registered);

        InitTitles();
        InitViews();
    }

    private void InitTitles() {
        setTitle(R.string.activity_layout_registered);
        setRightButtonImageAndListener(R.mipmap.close, mRegisteredListener);
    }

    private View.OnClickListener mRegisteredListener = new View.OnClickListener() {

        @Override
        public void onClick(View v) {
             back();
        }
    };

    private void back() {
        setViewPagerOutAnimation();
        // 如果是第一个页面则finish，如果不是，则显示上一个view
        if (mFlipper.getCurrentView().getId() == R.id.register_activity_first_view) {
            finish();
            return;
        }
        mFlipper.showPrevious();
    }

    private void InitViews() {
        mFlipper= (ViewFlipper) findViewById(R.id.register_activity_view_flipper);
        // first
        mEditPhone = (EditText)mFlipper.getChildAt(REGISTER_PAGE_1). findViewById(R.id.registered_phone);
        mBtnNextStep1 = (Button) mFlipper.getChildAt(REGISTER_PAGE_1).findViewById(R.id.registered_activity_layout_button_1);
        // second
        mEditCode = (EditText) mFlipper.getChildAt(REGISTER_PAGE_2).findViewById(R.id.registered_valid_code);
        mBtnCode = (Button) mFlipper.getChildAt(REGISTER_PAGE_2).findViewById(R.id.registered_verification_code_button);
        mBtnNextStep2 = (Button)mFlipper.getChildAt(REGISTER_PAGE_2). findViewById(R.id.registered_activity_layout_button_2);
        // third
        mEditPassword = (EditText) mFlipper.getChildAt(REGISTER_PAGE_3).findViewById(R.id.registered_password);
        mButtonRegister = (Button) mFlipper.getChildAt(REGISTER_PAGE_3). findViewById(R.id.registered_activity_layout_button_3);

        mBtnNextStep1.setOnClickListener(this);
        mBtnCode.setOnClickListener(this);
        mBtnNextStep2.setOnClickListener(this);
        mButtonRegister.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.registered_activity_layout_button_1:
                startActivity(new Intent(this, WelcomeActivity.class));
                doNextStepFirst();
                break;
            case R.id.registered_activity_layout_button_2:
                doNextStepSecond();
                break;
            case R.id.registered_verification_code_button: // 发送验证码
                mUserName = mEditPhone.getText().toString();
                if(StrUtils.isEmpty(mUserName)){
                    showToast(R.string.forget_password_activity_phone_not_null);
                    return;
                }
                sendValidCode(UrlContext.Url_CHECKMOBLE.getContext(), mUserName);
                startCount();
               // checkPhoto();
                break;
            case R.id.registered_activity_layout_button_3:  // 注册
                 register();
                break;
        }
    }

    private void doNextStepFirst() {
        setViewPagerInAnimation();
        mUserName = mEditPhone.getText().toString();
        if(StrUtils.isEmpty(mUserName)){
            showToast(R.string.register_activity_toast_enter_user_name);
            return;
        }
        mFlipper.showNext();
    }

    private void doNextStepSecond() {
        setViewPagerInAnimation();
        mValidCode = mEditCode.getText().toString();
        if(StrUtils.isEmpty(mValidCode) || mValidCode.length() < 6){
            showToast(R.string.register_activity_toast_enter_verification_code);
            return;
        }
        checkValidCode() ;
    }

    private void checkValidCode() {
        VerifyCodeRequest request = new VerifyCodeRequest(mUserName, mValidCode);
        mAsycHttpRequest.doRequest(this, request, BaseHttpResponse.class, mCallbackHandler, true);
    }

    private Handler mCallbackHandler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            mFlipper.showNext();
        }
    };

    // 下一步的animation
    private void setViewPagerInAnimation() {
        mFlipper.setInAnimation(getApplicationContext(), R.anim.in_right_left);
        mFlipper.setOutAnimation(getApplicationContext(), R.anim.out_right_left);
    }

    // 上一步的animation
    private void setViewPagerOutAnimation() {
        mFlipper.setInAnimation(getApplicationContext(), R.anim.in_left_right);
        mFlipper.setOutAnimation(getApplicationContext(), R.anim.out_left_right);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
       if(keyCode == KeyEvent.KEYCODE_BACK){
           back();
           return true;
       }
        return super.onKeyDown(keyCode, event);
    }

    private void checkPhoto() {
        /*if(mEditPhone !=null){
            sendValidCode(UrlContext.Url_CHECKMOBLE.getContext(), mUserName);
            startCount();
            return;
        }
        mUserName = mEditPhone.getText().toString();
            if(StrUtils.isEmpty(mUserName)){
                showToast(R.string.forget_password_activity_phone_not_null);
                return;
            }
            checkCode();*/
        }

    private void checkCode() {
            /*mValidCode = mEditCode.getText().toString();
            if(StrUtils.isEmpty(mValidCode) || mValidCode.length() < 6){
                showToast(R.string.activity_layout_shuru_yanzheng_ok);
                return;
            }
            checkValidCode();*/
    }



    private void register() {
        if(checkUserEnterThird()){
           RegisterRequest request = new RegisterRequest(mUserName, mValidCode, mPassword, mDevices);
           mAsycHttpRequest.doRequest(this, request, BaseHttpResponse.class, mRegisterHandler, true);
        }
      //  startActivity(new Intent(RegisteredActivity.this, PhotoMyActivity.class));
    }

    private Handler  mRegisterHandler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            showToast(R.string.registered_activity_toast_successful);
            setResult(Activity.RESULT_OK);
            finish();
        }
    };

    private boolean checkUserEnterThird() {
       /* mUserName = mEditPhone.getText().toString();
        mValidCode = mEditCode.getText().toString();*/
        mPassword = mEditPassword.getText().toString();
        /*if(StrUtils.isEmpty(mUserName)){
            showToast(R.string.activity_layout_edit_view_phone);
            return false;
        }
        if(StrUtils.isEmpty(mValidCode)){
            showToast(R.string.activity_layout_shuru_yanzheng);
            return false;
        }
        if(mValidCode.length() == Constants.VALID_CODE_LENGTH){
             showToast(R.string.activity_layout_shuru_yanzheng_ok);
            return false;
        }*/
        if(StrUtils.isEmpty(mPassword)){
            showToast(R.string.login_activity_toast_enter_password);
            return false;
        }
        if(mPassword.length() < Constants.PASSWORD_MIN_LENGTH ){
            showToast(R.string.activity_layout_view_hint_password);
            return false;
        }
        return true;
    }

    // 倒记计时器
    private Handler mHandler;
    private static final int COUNT_MAX = 61;
    private int    mCurrent;
    private boolean  mIsCounting;

    private void startCount() {
       if(mIsCounting){
              return;
       }
       mIsCounting = true;
       mBtnCode.setEnabled(false);
       mCurrent = 0;
       if(mHandler == null){
           mHandler = new Handler(new Handler.Callback() {
               @Override
               public boolean handleMessage(Message msg) {
                   mCurrent++;
                   if(COUNT_MAX - mCurrent > 0){
                       mBtnCode.setText(getString(R.string.activity_send_verification_code_button_ing, COUNT_MAX - mCurrent));
                       mHandler.sendEmptyMessageDelayed(0, 1000);
                   }else{
                       mBtnCode.setText(R.string.activity_send_verification_code_button);
                       mBtnCode.setEnabled(true);
                       mIsCounting = false;
                   }
                   return true;
               }
           });
       }
       mHandler.sendEmptyMessage(0);
    }

    public void onResume() {
        super.onResume();
        MobclickAgent.onResume(this);
    }

    public void onPause() {
        super.onPause();
        MobclickAgent.onPause(this);
    }
}
